
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from generate_panel_image import PanelImage
from custom_logger import PrefixDateLogger

logger = PrefixDateLogger("send_data_email")
class SendEmail:

    def __init__(self):
        # 邮件配置 (以QQ邮箱为例，其他邮箱请修改对应SMTP服务器和端口)
        self.email_config = {
            'smtp_server': 'smtp.126.com',
            'smtp_port': 465,
            'sender': 'chuays@126.com',
            'password': 'QAj6nezE5Ec3fSsj',
            'receivers': ['54269573@qq.com']  # 接收人列表
        }


    def send_email_with_screenshot(self,title,body,image_path):
        """发送带截图附件的邮件"""
        # 构造邮件
        msg = MIMEMultipart()
        msg["Subject"] = title
        msg['From'] = self.email_config['sender']
        msg['To'] = ','.join(self.email_config['receivers'])


        msg.attach(MIMEText(body, "html", "utf-8"))

        # 附加截图
        with open(image_path, "rb") as f:
            img = MIMEImage(f.read())
            img.add_header('Content-ID', '<graph1>')   # HTML 里 cid:graph1 对应这里
            img.add_header('Content-Disposition', 'inline')  #  inline 表示内嵌，非附件
            msg.attach(img)

        # 3. 发送邮件
        try:
            # 发送邮件
            with smtplib.SMTP_SSL(self.email_config['smtp_server'], self.email_config['smtp_port']) as server:
                server.login(self.email_config['sender'], self.email_config['password'])
                server.send_message(msg)
                server.quit()
            logger.info("邮件发送成功！")
        except Exception as e:
            logger.info(f"邮件发送失败：{str(e)}")

    def send_email_with_attachment(self,title,body,image_path):
        """发送带截图附件的邮件"""
        # 构造邮件
        msg = MIMEMultipart()
        msg["Subject"] = title
        msg['From'] = self.email_config['sender']
        msg['To'] = ','.join(self.email_config['receivers'])


        msg.attach(MIMEText(body, "html", "utf-8"))

        # 附加截图
        with open(image_path, "rb") as f:
            img = MIMEImage(f.read())
            img.add_header("Content-Disposition", f"attachment; filename={image_path}")
            msg.attach(img)

        # 3. 发送邮件
        try:
            # 发送邮件
            with smtplib.SMTP_SSL(self.email_config['smtp_server'], self.email_config['smtp_port']) as server:
                server.login(self.email_config['sender'], self.email_config['password'])
                server.send_message(msg)
                server.quit()
            logger.info("邮件发送成功！")
        except Exception as e:
            logger.info(f"邮件发送失败：{str(e)}")


# 执行脚本
if __name__ == "__main__":

    body=""
    image_path=""
    email=SendEmail()
    email.send_email_with_screenshot(body,image_path)